package cn.usian.service.impl;

import cn.usian.common.R;
import cn.usian.dao.CategoryDao;
import cn.usian.dao.DishDao;
import cn.usian.dao.SetmealDao;
import cn.usian.entity.Category;
import cn.usian.entity.Dish;
import cn.usian.entity.Setmeal;
import cn.usian.exception.CustomerException;
import cn.usian.exception.NameException;


import cn.usian.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Resource
    private CategoryDao categoryMapper;
    @Resource
    private DishDao dishDao;
    @Resource
    private SetmealDao setmealDao;

    @Override
    public R<Page<Category>> findPage(int page, int pageSize) {
        Page<Category> categoryPage = new Page<>(page, pageSize);
        Page<Category> selectPage = categoryMapper.selectPage(categoryPage, null);

        return R.success(selectPage);
    }

    @Override
    public void add(Category category) {
        /*//1.查询用户是否存在==>根据用户名查询用户的信息
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //添加用户名作为条件
        queryWrapper.eq(Category::getName,category.getName());
        //执行查询
        Category selectOne = categoryMapper.selectOne(queryWrapper);
        if(selectOne!=null){
            throw new NameException(category.getName());
        }*/
        //添加菜品的创建时间
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        //执行添加操作
        categoryMapper.insert(category);
    }

    @Override
    public void del(Long id) {
        //先根据id查询dish表的setmeal表中是否存在关联数据
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getCategoryId,id);
        List<Dish> dishList=dishDao.selectList(queryWrapper);
        if(!dishList.isEmpty()){
            throw  new CustomerException("该分类已关联其他菜品不能删除");
        }
        LambdaQueryWrapper<Setmeal> queryWrapper01 = new LambdaQueryWrapper<>();
        queryWrapper01.eq(Setmeal::getCategoryId,id);
        List<Setmeal> setmealList=setmealDao.selectList(queryWrapper01);
        if(!setmealList.isEmpty()){
            throw  new CustomerException("该分类已关联其他菜品不能删除");
        }
        categoryMapper.deleteById(id);
    }

    @Override
    public void update(Category category) {
        categoryMapper.updateById(category);
    }

    @Override
    public List<Category> findAll() {

        return categoryMapper.selectList(null);
    }

    @Override
    public R list(int type) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
       queryWrapper.eq(Category::getType,type);
        return R.success(categoryMapper.selectList(queryWrapper));
    }
}
